<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目标题" prop="xmflTitle">
        <el-input
          v-model="queryParams.xmflTitle"
          placeholder="请输入项目标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="xmflStatus">
        <el-select v-model="queryParams.xmflStatus" @change="handleQuery" placeholder="请选择启用状态" clearable>
          <el-option
            v-for="dict in tc_qyzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tc:tctype:add']"
        >新增</el-button>
      </el-col>
<!-- 	  
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tc:tctype:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tc:tctype:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tc:tctype:export']"
        >导出</el-button>
      </el-col>
	  -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  :show-overflow-tooltip="true" v-loading="loading" :data="tctypeList" @selection-change="handleSelectionChange">
	  <el-table-column label="项目标题" align="center" prop="xmflTitle" />
      <el-table-column label="启用状态" align="center" prop="xmflStatus">
        <template #default="scope">
          <dict-tag :options="tc_qyzt" :value="scope.row.xmflStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handlelook(scope.row)" >查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasRole="['admin', 'common']" v-hasPermi="['tc:tctype:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasRole="['admin', 'common']" v-hasPermi="['tc:tctype:remove']">删除</el-button>
        </template>
      </el-table-column>
	  
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评分标准对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tctypeRef" :model="form" :rules="rules" label-width="80px" :disabled="auform">
        <el-form-item label="项目标题" prop="xmflTitle">
          <el-input v-model="form.xmflTitle" placeholder="请输入项目标题" />
        </el-form-item>
        <el-form-item label="启用状态" prop="xmflStatus">
          <el-select v-model="form.xmflStatus" placeholder="请选择启用状态">
            <el-option
              v-for="dict in tc_qyzt"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">评分标准 - 项目</el-divider>
		
        <el-table :data="tcProjectList" @selection-change="handleTcProjectTpSelectionChange" ref="tcProjectTpRef" max-height="400">
          <el-table-column type="selection" width="50" align="center" prop="id" />
			<el-table-column type="index" label="序号" width="55" />
          <el-table-column label="名称" align="center" prop="xmMc"/>
        </el-table>
      </el-form>
      <template #footer  v-if="auform == false">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tctype">
import { listTctype, getTctype, delTctype, addTctype, updateTctype } from "@/api/tc/tctype";
import { listProject} from "@/api/tc/project";

const { proxy } = getCurrentInstance();
const { tc_qyzt } = proxy.useDict('tc_qyzt');

const tcProjectTpRef =  ref(null);
const tctypeList = ref([]);
const tcProjectList = ref([]);
const tcProjectTpList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTcProjectTp = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const idShowFlag = ref(false);
const auform = ref(true);
const tmpProPar={pageNum: 1,pageSize: 999,xmStatus:'1'};

// const toggleSelection = () => {
// 	if(tcProjectTpRef.value!=null){
// 		tcProjectTpRef.value.clearSelection();//清空复选框
// 	}
// }
const toggleSelection = (rows) => {
	      // proxy.$refs["tcProjectTpRef"].toggleRowSelection(row);
			// console.log(proxy.$refs["tcProjectTpRef"])  
		if (rows) {
			// console.log(tcProjectTpRef.value)  
			// console.log(proxy.$refs["tcProjectTpRef"])  
			rows.forEach((row) => {
			  // TODO: improvement typing when refactor table
			  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
			  // @ts-expect-error
			  if(tcProjectTpRef.value!=null){
				  // console.log(row)
				  for(let i of tcProjectList.value){
					  if(i.id == row.projectid) tcProjectTpRef.value.toggleRowSelection(i,true);
				  }
				}
			})
		} else {
			// tcProjectTpRef.value!.clearSelection()
			if(tcProjectTpRef.value!=null){
				tcProjectTpRef.value.clearSelection();//清空复选框
			}
		}
	

}



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    xmflTitle: null,
    xmflXxid: null,
    xmflMr: null,
    xmflStatus: '1',
  },
  rules: {
    xmflTitle: [
      { required: true, message: "项目标题不能为空", trigger: "blur" }
    ],
    xmflXxid: [
      { required: true, message: "学校不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

 onMounted(() => {
      // console.log('组件已经挂载')
	 //  nextTick(() => {
	 //        // proxy.$refs["tcProjectTpRef"].toggleRowSelection(row);
		// console.log(proxy.$refs["tcProjectTpRef"])
	 //  });
	  getList();
 })

/** 查询体测项目列表 */
function getProjectList() {
  loading.value = true;
  listProject(tmpProPar).then(response => {
    tcProjectList.value = response.rows;
    loading.value = false;
  });
}

/** 查询评分标准列表 */
function getList() {
  loading.value = true;
  listTctype(queryParams.value).then(response => {
    tctypeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
	getProjectList();
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    xmflTitle: null,
    xmflXxid: null,
    xmflMr: null,
    xmflStatus: '1',
    xmflDel: null,
    xmflCreate: null,
    xmflCreateby: null,
    xmflUpdate: null,
    xmflUpdateby: null
  };
  tcProjectTpList.value = [];
  checkedTcProjectTp.value=[];
  toggleSelection();
  proxy.resetForm("tctypeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  auform.value=false;
  reset();
  open.value = true;
  title.value = "添加评分标准";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  auform.value=false;
  reset();
  const _id = row.id || ids.value
  getTctype(_id).then(response => {
    form.value = response.data;
    // tcProjectTpList.value = response.data.tcProjectTpList;
	// checkedTcProjectTp.value = response.data.tcProjectTpList;
	// console.log(tcProjectList.value)
	
    open.value = true;
    title.value = "修改评分标准";
	nextTick(() => {
	  // console.log(tcProjectTpRef.value)
		toggleSelection(response.data.tcProjectTpList);
	});
  });
}
/** 查看按钮操作 */
function handlelook(row) {
  auform.value=true;
  reset();
  const _id = row.id || ids.value
  getTctype(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改评分标准";
	nextTick(() => {
		toggleSelection(response.data.tcProjectTpList);
	});
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["tctypeRef"].validate(valid => {
    if (valid) {
      // form.value.tcProjectTpList = tcProjectTpList.value;
	  form.value.tcProjectTpList = checkedTcProjectTp.value;
	  // console.log(form.value)
      if (form.value.id != null) {
        updateTctype(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
		form.value.tcProjectTpList = checkedTcProjectTp.value;
		console.log(form.value)
        addTctype(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除评分标准编号为"' + _ids + '"的数据项？').then(function() {
    return delTctype(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 评分分类项目序号 */
function rowTcProjectTpIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 评分分类项目添加按钮操作 */
function handleAddTcProjectTp() {
  let obj = {};
  tcProjectTpList.value.push(obj);
}

/** 评分分类项目删除按钮操作 */
function handleDeleteTcProjectTp() {
  if (checkedTcProjectTp.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的评分分类项目数据");
  } else {
    const tcProjectTps = tcProjectTpList.value;
    const checkedTcProjectTps = checkedTcProjectTp.value;
    tcProjectTpList.value = tcProjectTps.filter(function(item) {
      return checkedTcProjectTps.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTcProjectTpSelectionChange(selection) {
  // checkedTcProjectTp.value = selection.map(item => item.id)
  checkedTcProjectTp.value = selection.map(item => {return {"typeid":null,"projectid":item.id}});
  // console.log(checkedTcProjectTp.value);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tc/tctype/export', {
    ...queryParams.value
  }, `tctype_${new Date().getTime()}.xlsx`)
}

</script>
